<script setup>
import { onMounted, ref } from "vue";
import { readMaterial, updateMaterial } from "@/apis/material";
import { getCategoryList } from "@/apis/category";
import { useRoute, useRouter } from "vue-router";
import defaultImg from "@/assets/material.png";
import { Message } from "tdesign-mobile-vue";
import SelectWarehouseComponent from "@/components/Warehouse/SelectComponent.vue";
import { useUserStore } from "@/stores/user";
import { DTPWeb } from "dtpweb"

const store = useUserStore()
const route = useRoute();
const router = useRouter();
const fileList = ref([]);
const typeText = ref('');
const typeShow = ref(false);
const typeValue = ref([]);
let cateList = [[]];
const formData = ref({
  id: "",
  category_id: 0,
  cover: "",
  name: "",
  unit: "",
  specs: "",
  total: 0,
  bar_code: "",
  material_id: "",
  notes: "",
  price: 0,
  warehouse_id: 0,
  warehouse: {
    name: ""
  }
})
const isLoading = ref(false);
const ATTACH_URL = import.meta.env.VITE_ATTACH_URL;
const visible = ref(false)
let printer = DTPWeb.getInstance();

onMounted(() => {
  readMaterial(route.params.id)
    .then(res => {
      const { code, data } = res.data;
      if (code === 1) {
        formData.value = data;
        if (!data.cover) data.cover = defaultImg;
        fileList.value = [{
          url: data.cover_info.url,
          key: data.cover
        }]
        typeValue.value = [data.category_id];
        typeText.value = data.category.name;
      }
    })

  getCategoryList()
    .then(res => {
      const { code, data } = res.data;
      if (code === 1) {
        const option = [];
        data.forEach(element => {
          option.push({
            label: element.name,
            value: element.id
          })
        });
        cateList = [option];
      }
    })

  if (!isMobile()) {
    DTPWeb.checkServer((value) => {
      if (value) {
        printer = value;
      } else {
        Message.error({
          content: '打印组件插件异常',
          context: document.querySelector('main'),
          offset: [8, 8],
        })
      }
    })
  }

})

function isMobile() {
  if (window.navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)) {
    return true; // 移动端
  } else {
    return false; // PC端
  }
}

function formatRes(e) {
  if (e.code === 1) {
    formData.value.cover = e.data
    return {
      url: e.data
    }
  } else {
    return {
      error: e.msg,
    }
  }
}

function onPicker(value, context) {
  const label = context.label[0];
  formData.value.cate_id = value[0];
  typeText.value = label;
  typeShow.value = false
}

function scanCode() {

}

function selectWarehouseConfirm(item) {
  formData.value.warehouse = item.name;
  formData.value.warehouse_id = item.id;
  visible.value = false;
}

function save() {
  isLoading.value = true;
  updateMaterial(route.params.id, formData.value)
    .then(res => {
      const { code, msg } = res.data;
      if (code === 1) {
        Message.success({
          content: msg,
          context: document.querySelector('main'),
          offset: [8, 8],
        })
        setTimeout(() => {
          router.back();
        }, 2000);
      } else {
        Message.error({
          content: msg,
          context: document.querySelector('main'),
          offset: [8, 8],
        })
      }
    })
    .finally(() => {
      isLoading.value = false;
    })
}

function print() {
  printer.openPrinter((status) => {
    if (!status) {
      Message.error({
        content: '打印机连接异常',
        context: document.querySelector('main'),
        offset: [8, 8],
      })
      return;
    }

    printer.startJob({ width: 40, height: 60 });
    printer.drawText({
      text: '数控制造协会物资标签',
      x: 2.28,
      y: 0.5,
      width: 26,
      fontHeight: 3.88
    })
    printer.draw2DQRCode({
      text: formData.value.material_id,
      x: 28.24,
      y: 0.67,
      width: 8,
      height: 8
    })
    printer.drawText({
      text: "名称：" + formData.value.name,
      x: 2.28,
      y: 8.9,
      width: 40,
      fontHeight: 3
    })
    printer.drawText({
      text: "型号：" + formData.value.specs,
      x: 2.28,
      y: 12.9,
      width: 40,
      fontHeight: 3
    })
    printer.drawText({
      text: "编码：" + formData.value.material_id,
      x: 2.28,
      y: 16.9,
      width: 40,
      fontHeight: 3
    })
    printer.commitJob(() => {
      Message.success({
        content: '打印成功',
        context: document.querySelector('main'),
        offset: [8, 8],
      })
    })
  })
}
</script>
<template>
  <main>
    <t-form label-width="120">
      <t-cell-group title="物品信息">
        <t-form-item label="物品图片">
          <t-upload v-model="fileList" :multiple="false" :max="1" :size-limit="{ size: 20, unit: 'MB' }" accept="image/*"
            capture :action="ATTACH_URL" :headers="{ Authorization: store.token }" :formatResponse="formatRes">
          </t-upload>
        </t-form-item>
        <t-form-item requiredMark label="物品名称">
          <t-input name="name" v-model="formData.name" placeholder="物品名称" borderless></t-input>
        </t-form-item>
        <t-form-item label="计量单位">
          <t-input name="unit" v-model="formData.unit" placeholder="个/件/箱/斤/吨" borderless></t-input>
        </t-form-item>
        <t-form-item label="物品规格">
          <t-input name="norms" v-model="formData.specs" placeholder="20*20*20(选填)" borderless></t-input>
        </t-form-item>
        <t-form-item label="物品类型">
          <t-input name="cate_id" v-model="typeText" readonly borderless @click="typeShow = true"></t-input>
          <t-popup v-model="typeShow" placement="bottom">
            <t-picker v-model="typeValue" :columns="cateList" @cancel="typeShow = false" @confirm="onPicker" />
          </t-popup>
        </t-form-item>
        <t-form-item label="所在仓库">
          <t-input v-model="formData.warehouse.name" @click="visible = true" readonly borderless
            placeholder="请选择仓库"></t-input>
        </t-form-item>
        <t-form-item label="物品数量">
          <t-input v-model="formData.total" type="number" borderless></t-input>
        </t-form-item>
        <t-form-item label="物品单价">
          <t-input name="price" v-model="formData.price" type="number" borderless></t-input>
        </t-form-item>
        <t-form-item label="物品编码">
          <t-input v-model="formData.material_id" borderless disabled></t-input>
        </t-form-item>
        <t-form-item label="物品条码">
          <t-input v-model="formData.bar_code" borderless placeholder="选填">
            <template #suffixIcon>
              <t-icon @click="scanCode" name="scan" />
            </template>
          </t-input>
        </t-form-item>
        <t-form-item label="备注信息" bordered="false">
          <t-input v-model="formData.notes" borderless></t-input>
        </t-form-item>
      </t-cell-group>
    </t-form>
    <div style="margin: 8px;">
      <t-button type="submit" @click="save" :loading="isLoading" theme="primary" block>保存</t-button>
      <t-button type="button" @click="print" block style="margin-top: 6px">打印物资标签</t-button>
    </div>

    <t-popup v-model="visible" placement="bottom">
      <div class="header">
        <div class="btn btn--cancel" @click="visible = false">
          <t-icon name="chevron-down"></t-icon>
        </div>
        <div class="title">请选择仓库</div>
        <div class="btn btn--confirm" @click="visible = false"></div>
      </div>
      <SelectWarehouseComponent @confirm="selectWarehouseConfirm" />
    </t-popup>
  </main>
</template>

<style scoped lang="less">
.header {
  display: flex;
  align-items: center;
  height: 116rpx;
}

.title {
  flex: 1;
  text-align: center;
  font-weight: 600;
  font-size: 18px;
  color: var(--td-text-color-primary, rgba(0, 0, 0, 0.9));
}

.btn {
  font-size: 16px;
  padding: 16px;
}

.btn--cancel {
  color: var(--td-text-color-secondary, rgba(0, 0, 0, 0.6));
}

.btn--confirm {
  color: #0052d9;
  width: 20px;
  height: 20px;
}
</style>